package com.ocean.system.controller;

import com.ocean.common.annotation.Log;
import com.ocean.common.core.controller.BaseController;
import com.ocean.common.core.domain.AjaxResult;
import com.ocean.common.core.domain.entity.Config;
import com.ocean.common.core.domain.entity.SysUser;
import com.ocean.common.core.page.TableDataInfo;
import com.ocean.common.enums.BusinessType;
import com.ocean.common.utils.ShiroUtils;
import com.ocean.common.utils.poi.ExcelUtil;
import com.ocean.product.domain.OProduct;
import com.ocean.product.service.IOProductService;
import com.ocean.system.domain.*;
import com.ocean.system.mapper.ODownLogMapper;
import com.ocean.system.service.IODownOrderService;
import com.ocean.system.service.impl.ODownLogServiceImpl;
import com.ocean.workOrder.domain.OWorkOrder;
import com.ocean.workOrder.service.IOWorkOrderService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Controller
 *
 * @author ocean
 * @date 2022-12-05
 */
@Controller
@RequestMapping("/system/order")
public class ODownOrderController extends BaseController {
    private String prefix = "system/order";

    @Autowired
    private IODownOrderService oDownOrderService;
    @Autowired
    private IOWorkOrderService oWorkOrderService;
    @Autowired
    private IOProductService ioProductService;


    @RequiresPermissions("system:order:view")
    @GetMapping()
    public String order() {
        return prefix + "/orderdy";
    }

    @RequiresPermissions("system:order:view")
    @GetMapping("/xz/{ddid}")
    public String orderxz(@PathVariable String ddid ,ModelMap mmap) {
        mmap.addAttribute("ddid",ddid);
        return prefix + "/orderxz";
    }

    @RequiresPermissions("system:order:view")
    @GetMapping("/wxz")
    public String orderwxz() {
        return prefix + "/orderwxz";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ODownOrder oDownOrder) {
        startPage();
        List<ODownOrder> list = oDownOrderService.selectODownOrderList(oDownOrder);
        return getDataTable(list);
    }

    /*
     * 订阅单
     * */
    @RequiresPermissions("system:order:list")
    @PostMapping("/listdy")
    @ResponseBody
    public TableDataInfo listdy(Selectdy selectdy) {
        startPage();
        //oDownOrder.setStatus("0");
        List admin = null;
        //获取当前登录用户
        SysUser currentUser = ShiroUtils.getSysUser();
        if ("admin,管理员".contains(currentUser.getLoginName())){
            admin = oWorkOrderService.selectdy(selectdy);
        }else{
            selectdy.setReal_name(currentUser.getLoginName());
            admin = oWorkOrderService.selectdy(selectdy);
        }

        return getDataTable(admin);
    }

    /*
     * 下载单
     * */
    //@RequiresPermissions("system:order:listxz")
    @PostMapping("/listxz")
    @ResponseBody
    public TableDataInfo listxz(Selectxz selectxz) {
        startPage();
        //获取当前登录用户
        SysUser currentUser = ShiroUtils.getSysUser();
        if(!"admin,管理员".contains(currentUser.getLoginName())){//如果不是管理员账户 就通过当前登录账户查询当前用户的数据
            selectxz.setUser_id(Integer.parseInt(currentUser.getUserId().toString()));
        }
        //查询数据
        List<Selectxz> selectxz1 = oDownOrderService.selectxz1(selectxz);
        long size = oDownOrderService.selectxz1size(selectxz);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setTotal(size);
        //如果登录名不为空 就通过登录名查询
        if(!selectxz.getLogin_name().equals("")){
            List<Selectxz> collect = selectxz1.stream().filter(selectxz2 -> selectxz2.getLogin_name().equals(selectxz.getLogin_name())).collect(Collectors.toList());
            //如果结束时间为0 就通过结束时间为空查询
            if(selectxz.getDown_end_date().equals("0") && !selectxz.getDown_end_date().equals("")){
                List<Selectxz> collect1 = collect.stream().filter(selectxz2 -> selectxz2.getDown_end_date() == null).collect(Collectors.toList());
                tableDataInfo.setRows(collect1);
                return tableDataInfo;
                //如果结束时间为1 就通过结束时间不为空查询
            }else if(selectxz.getDown_end_date().equals("1") && !selectxz.getDown_end_date().equals("")){
                List<Selectxz> collect1 = collect.stream().filter(selectxz2 -> selectxz2.getDown_end_date() != null).collect(Collectors.toList());
                tableDataInfo.setRows(collect1);
                return tableDataInfo;
            }
            tableDataInfo.setRows(collect);
            return tableDataInfo;
        }
        //如果结束时间为0 就通过结束时间为空查询
        if(selectxz.getDown_end_date().equals("0") && !selectxz.getDown_end_date().equals("")){
            List<Selectxz> collect1 = selectxz1.stream().filter(selectxz2 -> selectxz2.getDown_end_date() == null).collect(Collectors.toList());
            return getDataTable(collect1);
            //如果结束时间为1 就通过结束时间不为空查询
        }else if(selectxz.getDown_end_date().equals("1") && !selectxz.getDown_end_date().equals("")){
            List<Selectxz> collect1 = selectxz1.stream().filter(selectxz2 -> selectxz2.getDown_end_date() != null).collect(Collectors.toList());
            return getDataTable(collect1);
        }
        return getDataTable(selectxz1);
    }

    /*@PostMapping("/upzt")
    @ResponseBody
    public boolean upzt(String down_id) {
        ODownOrder o = new ODownOrder();
        o.setDownNo(down_id);
        o.setStatus("0");
        List<ODownOrder> oDownOrders = oDownOrderService.selectODownOrderList(o);
    }*/
    /**
     * 已下载，在页面上下载状态为2
     *
     * @param oDownOrder
     * @return
     */
    //@RequiresPermissions("system:order:listwxz")
    @PostMapping("/listwxz")
    @ResponseBody
    public TableDataInfo listwxz(Selectwxz selectwxz) {
        startPage();
        SysUser currentUser = ShiroUtils.getSysUser();
        if(!"admin,管理员".contains(currentUser.getLoginName())){
            selectwxz.setUser_id(Integer.parseInt(currentUser.getUserId().toString()));
        }
        List<Selectwxz> list = oDownOrderService.selectwxz(selectwxz);
        return getDataTable(list);
    }
    /**
     * 查看网页端下载数据
     */
    @PostMapping("/wydxz")
    @ResponseBody
    public TableDataInfo wydxz(ODownwebDwon oDownwebDwon) {
        startPage();
        SysUser currentUser = ShiroUtils.getSysUser();
        if(!"admin,管理员".contains(currentUser.getLoginName())){
            oDownwebDwon.setUserid(currentUser.getUserId().toString());
        }
        List<ODownwebDwon> list = oDownOrderService.selectwydxz(oDownwebDwon);
        return getDataTable(list);
    }
    // 字节转兆字节（MB）
    private static double bytesToMegabytes(long bytes) {
        return bytes / (1024.0 * 1024.0); // 精确浮点计算
    }
    /**
     * 新增网页端下载数据
     * @param oDownwebDwon
     * @return
     */
    @PostMapping("/tjwyxzsj")
    @ResponseBody
    public void tjwyxzsj(ODownwebDwon oDownwebDwon) {
        SysUser currentUser = ShiroUtils.getSysUser();
        oDownwebDwon.setUserid(currentUser.getUserId().toString());
        File file = new File(oDownwebDwon.getPath());
        if (!file.exists() || !file.isFile()) {
            throw new IllegalArgumentException("文件不存在或路径无效");
        }
        long fileSizeBytes = file.length();
        double v = bytesToMegabytes(fileSizeBytes);//转为M
        oDownwebDwon.setSize(v);//文件大小
        oDownwebDwon.setZt("2");
        oDownwebDwon.setCjr(currentUser.getUserName());
        oDownwebDwon.setCjsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if(!oDownwebDwon.getCp().contains(Config.ZNWG.getZnwg())){
            if(oDownwebDwon.getCp()==null){
                oDownwebDwon.setCp("未知");
                oDownOrderService.addwebdown(oDownwebDwon);
            }else{
                OProduct oProduct = ioProductService.selectOProductById(oDownwebDwon.getCp());
                oDownwebDwon.setCp(oProduct.getProductName());
                oDownOrderService.addwebdown(oDownwebDwon);
            }
        }else {
            oDownOrderService.addwebdown(oDownwebDwon);
        }
    }
    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:order:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ODownOrder oDownOrder) {
        List<ODownOrder> list = oDownOrderService.selectODownOrderList(oDownOrder);
        ExcelUtil<ODownOrder> util = new ExcelUtil<ODownOrder>(ODownOrder.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:order:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ODownOrder oDownOrder) {
        return toAjax(oDownOrderService.insertODownOrder(oDownOrder));
    }

    /**
     * 详情【请填写功能名称】
     */
    @RequiresPermissions("system:order:detail")
    @GetMapping("/detail/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        OWorkOrder workOrder = oWorkOrderService.selectOWorkOrderById(id);
        mmap.put("workOrder", workOrder);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:order:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ODownOrder oDownOrder) {
        return toAjax(oDownOrderService.updateODownOrder(oDownOrder));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:order:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(oDownOrderService.deleteODownOrderByIds(ids));
    }

    /**
     * 订阅单删除
     * @param ids
     * @return
     */
    @RequiresPermissions("system:order:removedy")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping("/removedy")
    @ResponseBody
    public AjaxResult removedy(String ids) {
        return toAjax(oWorkOrderService.deleteOWorkOrderByIds(ids));
    }

    /**
     * 订阅单管理-一键续订
     */
    @PostMapping("renewalProduct")
    @ResponseBody
    public AjaxResult renewalProduct(OWorkOrder workOrder, @RequestParam String work_type){
        workOrder.setWorkType(work_type);
        return oWorkOrderService.renewalProduct(workOrder);
    }


}
